package com.ruoyi.web.service;

import com.ruoyi.web.dao.DashboardMapper;
import com.ruoyi.web.model.Article;
import com.ruoyi.web.model.ContributionData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DashboardService {
    @Autowired
    private DashboardMapper dashboardMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public Integer getArticleCount() {
        return dashboardMapper.getArricleCount();
    }

    public Integer getUserCount() {
        return dashboardMapper.getUserCount();
    }

    public Integer getMessageCount() {
        return dashboardMapper.getMessageCount();
    }

    public Integer getVisitCount() {
        return dashboardMapper.getVisitCount();
    }

    public List<ContributionData> getContributionData() {
        return dashboardMapper.getContributionData();


    }

    public List<Map<String, Integer>> getBottomData() {
        return dashboardMapper.getBottomData();
    }

    public List<Integer> getBrowseTrendData(Integer days) {
        List<Integer> result = new ArrayList<>();
        LocalDate now = LocalDate.now();

        for (int i = days - 1; i >= 0; i--) {
            LocalDate date = now.minusDays(i);
            String key = "visit_count:" + date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            // 从Redis获取数据
            String value = stringRedisTemplate.opsForValue().get(key);
            if (value != null) {
                try {
                    result.add(Integer.parseInt(value));
                } catch (NumberFormatException e) {
                    result.add(0);
                }
            } else {
                result.add(0);
            }
        }

        return result;
    }
}
